package com.service.dialtest.service.impl;/**
 * @author ：hjl
 * @date ：Created in 2021/10/28 19:23
 * @description：
 */

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.service.config.dto.SiteDto;
import com.service.config.utils.IdUtil;
import com.service.dialtest.dao.CloudUserDao;
import com.service.dialtest.dto.CheckTenantDto;
import com.service.dialtest.dto.CloudUserDto;
import com.service.dialtest.dto.DialTestDto;
import com.service.dialtest.dto.DialTestDto2;
import com.service.dialtest.entity.CloudUserInfo;
import com.service.dialtest.service.CloudUserService;
import com.service.config.utils.ModelMapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.service.config.constant.ApiUrlConstants.*;

/**
 * @Description:
 * @Author: hjl
 * @Date: 2021/10/28 19:23
 */
@Service
@Slf4j
public class CloudUserServiceImpl implements CloudUserService {

    @Autowired
    RestTemplate restTemplate;
    @Resource
    private CloudUserDao cloudUserDao;

    /**
     * 校验云管api
     * @param checkTenantDto
     * @param userId
     * @return
     */
    @Override
    public Map check(CheckTenantDto checkTenantDto, String userId) {
        HashMap map = new HashMap();
        CloudUserInfo userInfo = new CloudUserInfo();
        userInfo.setTenantName(checkTenantDto.getUsername());
        HttpHeaders requestHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        requestHeaders.setContentType(type);
        requestHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        String token = getToken(checkTenantDto.getUsername(), checkTenantDto.getPassword(), requestHeaders, checkTenantDto.getDomain());
        if (token == null) {
            map.put("errorMsg", "华为云管理账号不存在");
        } else {
            //获取站点
            requestHeaders.add("X-AUTH-TOKEN", token);
            List<DialTestDto2> dataOfDialTest = getDataOfDialTest(requestHeaders, checkTenantDto.getDomain());
            if(null!=dataOfDialTest && dataOfDialTest.size()>0)
            {
                map.put("dataOfDialTest",dataOfDialTest);
                return map;
            }
            map.put("errorMsg", "该账号没有权限调用api");
        }
        return map;
    }

    @Override
    public List<CloudUserDto> queryAll(String userId) {
        CloudUserInfo cloudUserInfo = new CloudUserInfo();
        cloudUserInfo.setUserId(userId);
        List<CloudUserInfo> list = cloudUserDao.queryAll(cloudUserInfo);
        List<CloudUserDto> screenUserDtoList = ModelMapperUtil.strictMapList(list, CloudUserDto.class);
        return screenUserDtoList;
    }

    @Override
    public void serviceStatusBind(String cloud_user_id, Boolean status, String userId, String domain) {
        CloudUserInfo cloudUserInfo = new CloudUserInfo();
        cloudUserInfo.setUserId(userId);
        cloudUserInfo.setDomain(domain);
        List<CloudUserInfo> cloudUserInfos = cloudUserDao.queryAll(cloudUserInfo);
        if(null==cloudUserInfos || cloudUserInfos.size()==0)
        {
            return;
        }
        List<CloudUserInfo> collect = cloudUserInfos.stream().filter(cloudUserInfo1 -> !cloudUserInfo1.getId().equals(cloud_user_id)).collect(Collectors.toList());
        collect.stream().forEach(cloudUserInfo2 -> {
            if (status) {
                cloudUserInfo2.setStatus(true);
            }
        });
        List<CloudUserInfo> collect1 = cloudUserInfos.stream().filter(cloudUserInfo2 -> cloudUserInfo2.getId().equals(cloud_user_id)).collect(Collectors.toList());
        collect1.stream().forEach(cloudUserInfo1 -> {
            cloudUserInfo1.setUserId(userId);
            cloudUserInfo1.setId(cloud_user_id);
            cloudUserInfo1.setStatus(status);
        });
        cloudUserDao.insertOrUpdateBatch(cloudUserInfos);
    }

    @Override
    public boolean deleteById(String id) {
        return this.cloudUserDao.deleteById(id) > 0;
    }

    @Override
    public void updateApiAccount(CloudUserInfo strictMap) {
        cloudUserDao.update(strictMap);
    }

    @Override
    public List<CloudUserInfo> insertOrUpdate(CloudUserInfo strictMap, String userId) {
        CloudUserInfo cloudUserInfo = new CloudUserInfo();
        cloudUserInfo.setTenantName(strictMap.getTenantName());
        cloudUserInfo.setUserId(userId);
        cloudUserInfo.setDomain(strictMap.getDomain());
        List<CloudUserInfo> cloudUsers = cloudUserDao.queryAll(cloudUserInfo);
        if (cloudUsers.size() > 0) {
            return cloudUsers;
        } else {
            strictMap.setId(IdUtil.getStringId());
            strictMap.setUserId(userId);
            strictMap.setStatus(true);
            cloudUserDao.insert(strictMap);
            return null;
        }
    }

    /**
     * 获取站点site
     *
     * @param requestHeaders
     * @return
     */
    public List<DialTestDto2> getDataOfDialTest(HttpHeaders requestHeaders, String domain) {
        //获取站点
        boolean flag = true;
        int pageIndex = 1;
        List<DialTestDto2> siteDtos = new ArrayList<>();
        try {
            while (flag) {
                HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
                ResponseEntity<JSONObject> response = restTemplate.exchange("https://" + domain + SITE_URL + pageIndex, HttpMethod.GET, requestEntity, JSONObject.class);
                JSONArray data = response.getBody().getJSONArray("data");
                if (!data.isEmpty()) {
                    System.out.println(data.toJavaList(SiteDto.class));
                    siteDtos.addAll(getDialTest());
                    pageIndex++;
                } else {
                    flag = false;
                }
            }
            return siteDtos;
        } catch (Exception e) {
            log.error("debug getSites ==>" + e.getMessage());
            return null;
        }
    }

    private List<DialTestDto2> getDialTest() {
        List<DialTestDto2> dialTestDtos=new ArrayList<>();
        DialTestDto2 dialTestDto1=new DialTestDto2("TAH","Shangri-La Tanjung Aru","",60,8,7.5f,5,46,36.83f,1.52f,8.44f,5.08f,0.79f,39.72f,6.98f,-85,-14,-52,5,8,0.08f,0.13f,0.78f,0);
        DialTestDto2 dialTestDto2=new DialTestDto2("RRR","Shangri-La Rasa Ria Resort","HUAWEI JSN-L22,HUAWEI",265,14,18.9f,3,5289,512.84f,0f,94f,6.05f,0f,19.89f,5.62f,-91,-22,-58,5,42,0.16f,0.14f,0.7f,0);
        DialTestDto2 dialTestDto3=new DialTestDto2("SLWZ","Shangri-la WenZhou","Samsung Galaxy Note8",28,5,5.6f, 19.19f,160.8f,48.95f, 0.46f,14.49f,7.88f, 0.66f,9.49f,8.22f, 0,0,0, 0,0,0f,0f,0f,0);
        DialTestDto2 dialTestDto4=new DialTestDto2("SLTJ","Shangri-La Tian Jin","",2,1,2.0f,84,85,84.5f,10.65f,10.72f,10.69f,11.39f,11.46f,11.43f,-52,-51,-52,0,0,0f,0f,1f,0);
        DialTestDto2 dialTestDto5=new DialTestDto2("SLAD","Shangri-La Abu Dhabi","",21,3,7.0f,71,100,75.62f,8.72f,23.97f,18.42f,6.07f,24.5f,15.77f,-82,-35,-57,4,3,0.19f,0.14f,0.67f,0);
        DialTestDto2 dialTestDto6=new DialTestDto2("SLIB","Shangri-La Bosphorus Istanbul","",154,7,22.0f,52,70,55.75f,9.23f,38.07f,19.94f,8.9f,50.58f,33.61f,-64,-28,-55,0,0,0f,0f,1.0f,0);
        DialTestDto2 dialTestDto7=new DialTestDto2("HJHK","Hotel Jen Hong Kong","",116,12,9.7f,36,58,38.53f,0.74f,26.12f,20.16f,0f,30.71f,18.52f,-85,-32,-54,18,9,0.16f,0.08f,0.77f,0);
        DialTestDto2 dialTestDto8=new DialTestDto2("KHPU","Kerry Hotel Pudong Shanghai","",32,6,5.3f,56,68,60.34f,10.09f,32.41f,20.4f,2.74f,36.97f,22.21f,-65,-31,-47,0,0,0f,0f,1f,0);
        DialTestDto2 dialTestDto9=new DialTestDto2("KSL","Kowloon Shangri-La,Hong Kong","",110,7,15.7f,38,999,50.1f,0.62f,39.39f,23.34f,0.36f,39.69f,22.24f,-77,-23,-52,6,11,0.05f,0.10f,0.85f,0);
        DialTestDto2 dialTestDto10=new DialTestDto2("KHHK","Kerry Hotel Hong Kong","",350,22,15.9f,35,999,49.95f,2.4f,56.35f,26.35f,3.03f,60.74f,32.98f,-78,-18,-45,10,13,0.03f,0.04f,0.93f,0);
        DialTestDto2 dialTestDto11=new DialTestDto2("HJTS","Hotel Jen Tanglin Singapore","Samsung Galaxy A50",68,10,6.8f,5,28,7.21f,4.96f,30.01f,26.7f,3.11f,30.38f,27.18f,-82,-32,-59,12,3,0.18f,0.04f,0.78f,7);
        DialTestDto2 dialTestDto12=new DialTestDto2("HBKC","Island Shangri-La Hotel,Hong Kong","Samsung Galaxy Note8",12,4,3.0f,55,62,57.67f,9.32f,42.48f,27.96f,12.03f,27.07f,22.31f,-71,-40,-53,1,0,0.08f,0f,0.92f,0);
        DialTestDto2 dialTestDto13=new DialTestDto2("SLPU","Shangri-La Hotel Shanghai","",135,8,16.9f,36,67,47.85f,18.4f,44.33f,32.41f,12.1f,41.73f,32.78f,-71,-1,-52,1,1,0.01f,0.01f,0.99f,0);
        DialTestDto2 dialTestDto14=new DialTestDto2("SLYZ","Shangri-La Hotel,Yangzhou","Huawei P9",121,10,12.1f,62,999,416.79f,4.18f,55.89f,32.64f,1.69f,46.42f,33.24f,-86,-29,-54,9,11,0.07f,0.09f,0.83f,9);
        DialTestDto2 dialTestDto15=new DialTestDto2("ISL","Island Shangri-La Hotel,Hong Kong","Samsung Galaxy Note 8",142,7,20.3f,36,54,40.08f,10.3f,109.83f,42.48f,6.27f,366.13f,56.14f,-75,-38,-57,8,21,0.06f,0.15f,0.8f,7);
        dialTestDtos.add(dialTestDto1);
        dialTestDtos.add(dialTestDto2);
        dialTestDtos.add(dialTestDto3);
        dialTestDtos.add(dialTestDto4);
        dialTestDtos.add(dialTestDto5);
        dialTestDtos.add(dialTestDto6);
        dialTestDtos.add(dialTestDto7);
        dialTestDtos.add(dialTestDto8);
        dialTestDtos.add(dialTestDto9);
        dialTestDtos.add(dialTestDto10);
        dialTestDtos.add(dialTestDto11);
        dialTestDtos.add(dialTestDto12);
        dialTestDtos.add(dialTestDto13);
        dialTestDtos.add(dialTestDto14);
        dialTestDtos.add(dialTestDto15);
        return dialTestDtos;
    }

    /**
     * 获取token
     *
     * @param username
     * @param password
     * @param requestHeaders
     * @return
     */
    public String getToken(String username, String password, HttpHeaders requestHeaders, String domain) {
        //获取token
        Map map = new HashMap();
        map.put("userName", username);
        map.put("password", password);
        try {
            HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
            ResponseEntity<JSONObject> response = restTemplate.exchange(URL_FIRST + domain + CLOUD_CAMPUS_TOKEN_URL, HttpMethod.POST, requestEntity, JSONObject.class);
            return response.getBody().getJSONObject("data").getString("token_id");
        } catch (Exception e) {
            log.error("debug Token ==>" + e.getMessage());
            return null;
        }
    }
}
